<template>
  <BasicDialog ref="basicDialog" :isVisible="isAlert" width="30%" :title="title" @handleSure="handleSure" :isShowSure="flag != 'role_look'">
    <template #content>
      <el-form ref="formRef" :model="formInfo" :rules="flag != 'role_look' ? rules : {}" label-width="120px">
        <el-form-item label="角色名称：" prop="rname">
          <el-input v-if="flag != 'role_look'" type="text" v-model.trim="formInfo.rname" />
          <span v-else>{{ formInfo.rname }}</span>
        </el-form-item>
        <el-form-item label="角色标识：" prop="code">
          <el-input v-if="flag != 'role_look'" type="text" v-model.trim="formInfo.code" />
          <span v-else>{{ formInfo.code }}</span>
        </el-form-item>
        <el-form-item label="菜单权限：" prop="menuIds">
          <el-cascader ref="cascaderRef" :options="menuObj.menusTree" :props="menuObj.props"
            placeholder="请选择菜单权限" v-model="formInfo.menuIds" collapse-tags collapse-tags-tooltip max-collapse-tags="7"
            clearable ></el-cascader>
        </el-form-item>
        <el-form-item label="数据权限类型：" prop="dataScope">
          <el-select v-if="flag != 'role_look'" v-model="formInfo.dataScope" placeholder="数据权限" clearable
            style="width: 100%">
            <el-option v-for="op in dataScope" :key="op.value" :value="op.value" :label="op.label" />
          </el-select>
          <span v-else>{{ dataScopeEnum[formInfo.dataScope] }}</span>
        </el-form-item>
        <el-form-item label="数据权限部门：" prop="deptIds" v-if="formInfo.dataScope == 4 || formInfo.dataScope == 5"
          :rules="[{required: true,message: '请选择权限部门',trigger: 'blur'}]">
          <el-tree-select
            v-model="formInfo.deptIds"
            value-key="id"
            :props="{label:'dname'}"
            :check-strictly="true"
            show-checkbox
            multiple
            :data="deptTreeData"
            :render-after-expand="false"
            style="width: 240px"
          />
        </el-form-item>
      </el-form>
    </template>
  </BasicDialog>
</template>
<script lang='ts' setup>
import { FormInfo } from "@components/common/BasicForm/BasicFormTypes";
import type { FormInstance, FormRules } from 'element-plus';
import { toTreeData } from "@/utils";
import { roleAdd, roleEdit, getRoleById } from "@/request/apis/system/role";
import { getActiontreeTree } from "@/request/apis/system/menu";
import { dataScope, dataScopeEnum } from "@/utils/staticData"
import { getOrgTree } from "@/request/apis/system/framework";

const props = defineProps({
  info: {
    type: Object,
    default: () => {
      return {}
    }
  },
  flag: {
    type: String,
    default: ''
  },
  isAlert: {
    type: Boolean,
    default: false
  },
  parentData: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const $emits = defineEmits([
  "closeDialog"
])

//表单数据 
let formInfo = ref<FormInfo>({});

const cascaderRef = ref()
let menuObj = reactive<FormInfo>({
  menusTree: [],  // 展示菜单选择的层级数据
  props: {
    //菜单权限的选择属性
    multiple: true,
    expandTrigger: "click",
    value: "id",
    label: "mname",
    emitPath: false
  },
  menuHalf: new Set(),  // 半选的菜单
})

// 表单校验规则
const rules = reactive<FormRules>({
  rname: [{ required: true, message: "不能为空", trigger: "blur" }],
  code: [{ required: true, message: "不能为空", trigger: "blur" }],
  dataScope: [{ required: true, message: "不能为空", trigger: "blur" }],
})

// 提交表单校验
const formRef = ref<FormInstance>();
const basicDialog = ref();

// 用来处理菜单选择的数据处理
function getHalfMenus() {
  menuObj.menuHalf.clear()
  const checkedNodes = cascaderRef.value.getCheckedNodes(true)
  checkedNodes.forEach((node:any) => {
    let len = node.pathValues.length
    for(let i = 0; i < len-1; i++){
      menuObj.menuHalf.add(node.pathValues[i]);
    }
  });
}
async function handleSure() {
  formRef.value.validate(valid => {
    if (valid) {
      basicDialog.value.changeLoading(true);
      getHalfMenus()
      let params = {
        ...formInfo.value,
        halfMenuIds: [...menuObj.menuHalf],
      }
      let funName = props.flag == 'role_add' ? roleAdd : roleEdit
      funName(params).then((res: any) => {
        ElMessage.success("操作成功")
        $emits("closeDialog", 1);
        basicDialog.value.changeLoading(false);
      }).catch(err => {
        basicDialog.value.changeLoading(false);
      })

    }
  })
}

// ---------------部门树---------------
//#region
const deptTreeData = ref([])

//监听dataScope变化
watch(
  () => formInfo.value.dataScope,
  (newValue, oldValue) => {
    if(newValue != 4 && newValue != 5){
      formInfo.value.deptIds = []
    }
  }
);

// 获取部门树形数据
function getDeptTreeData() {
  getOrgTree({id:null})
    .then((res: any) => {
      deptTreeData.value = toTreeData(res,"pid","id");
    })
    .catch((err) => { });
}
//#endregion

const title = ref("");
onMounted(async() => {
  if (props.flag == "role_add") {
    title.value = '新增'
  } else if (props.flag == "role_edit") {
    title.value = '修改'
    const data = await getRoleById(props.info.id)
    formInfo.value = data
  } else if (props.flag == "role_look") {
    title.value = '查看'
    const data = await getRoleById(props.info.id)
    formInfo.value = data
  }  
  // 获取菜单数据
  const menus = await getActiontreeTree({hasButton:true})
  menuObj.menusTree = toTreeData(menus,"pid","id");

  //获取机构树
  getDeptTreeData()

})

</script>

<style scoped lang="scss"></style>